const app = new Vue({
    el: '#app',
    data() {
        const rulesSNo = (rule,value,callback)=>{
            if(this.isEdit){
                callback();
            }
            axios.post(
                this.baseURL + '/sno/check/',
                {
                    sno:value,
                }
            )
            .then((res)=>{
                if(res.data.code === 1){
                    if(res.data.exists){
                        callback(new Error("学号已经存在!"));
                    }else{
                        callback();
                    }
                }else{
                    callback(new Error("校验学号后端出现异常"));   
                }
            })
            .catch((err)=>{
                console.log(err);
            })
;;        }
        return{
            msg: 'Hello,Vue!',
            baseURL: "http://127.0.0.1:8000/",
            students: [],
            pageStudents: [],
            inputStr: '',
            total: 100,
            currentpage: 1,
            pagesize: 10,
            dialogVisible: false,
            dialogTitle: "",
            isView: false,
            isEdit: false,
            imageUrl:"",
            selectStudents:[],
            studentForm: {
                sno: '',
                name: '',
                gender: '',
                birthday: '',
                moblie: '',
                email: '',
                address: '',
                image: '',
                imageUrl:''

            },
            rules: {
                sno: [
                    { required: true, message: '学号不能为空', trigger: 'blur' },
                    { pattern: /^[9][5]\d{3}$/, message: '学号必须是95开头的5位数', trigger: 'blur' },
                    { validator:rulesSNo,trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '姓名不能为空', trigger: 'blur' },
                    { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '姓名需要为2到5个汉字', trigger: 'blur' }
                ],
                gender: [
                    { required: true, message: '性别不能为空', trigger: 'change' },
                ],
                birthday: [
                    { required: true, message: '出生日期不能为空', trigger: 'change' },
                ],
                mobile: [
                    { required: true, message: '电话号码不能为空', trigger: 'blur' },
                    { pattern: /^[1][35989]\d{9}$/, message: '电话号码不许1开头带3589 ', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '邮箱不能为空', trigger: 'blur' },
                    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱地址要符合规范', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '家庭住址不能为空', trigger: 'change' },
                ]
            }
        }
    },
    mounted() {
        this.getStudents();
    },
    methods: {
        //获取所有学生的信息
        getStudents: function () {
            let _this = this;
            axios
                .get(_this.baseURL + 'students/')
                .then(function (res) {
                    if (res.data.code === 1) {
                        _this.students = res.data.data;
                        _this.total = res.data.data.length;
                        _this.getPageStudents();
                        _this.$message({
                            message: '数据加载成功！',
                            type: 'success'
                        });
                    } else {
                        _this.$message.error(res.data.msg);
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        },
        getPageStudents() {
            //清空pageStudents中的数据
            this.pageStudents = [];
            for (let i = (this.currentpage - 1) * this.pagesize; i < this.total; i++) {
                this.pageStudents.push(this.students[i]);
                if (this.pageStudents.length === this.pagesize) break;
            }
        },
        handleSizeChange(size) {
            this.pagesize = size;
            this.getPageStudents();
        },
        handleCurrentChange(pageNumber) {
            this.currentpage = pageNumber;
            this.getPageStudents();
        },
        queryStudents() {
            let that = this;
            axios
                .post(
                    that.baseURL + "students/query/",
                    {
                        inputstr: that.inputStr
                    }
                )
                .then(function (res) {
                    if (res.data.code === 1) {
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '查询数据成功！',
                            type: 'success'
                        });
                    } else {

                    }
                })
                .catch(function (err) {
                    console.log(err);
                    that.$message.error("查询结果出现异常");
                })
        },
        addStudent() {
            this.dialogTitle = "添加学生";
            this.dialogVisible = true;
        },
        updateStudent(row) {
            this.dialogTitle = "修改学生信息";
            this.isEdit = true;
            this.dialogVisible = true;
            this.studentForm = JSON.parse(JSON.stringify(row));
        },
        viewStudent(row) {
            this.dialogTitle = "查看学生明细";
            this.isView = true;
            this.dialogVisible = true;
            this.studentForm = JSON.parse(JSON.stringify(row));
        },
        submitStudentForm(formName){
            this.$refs[formName].validate((valid)=>{
                if(valid){
                    if(this.isEdit){
                        this.submitUpdateStudent();
                    } else{
                        this.submitAddStudent();
                    }
                    alert('submit!');
                } else {
                    console.log('err submit!');
                    return false;
                }
            });
        },
        submitAddStudent(){
            let that = this;
            axios
            .post(that.baseURL + 'student/add/',that.studentForm)
            .then(res=>{
                if(res.data.code === 1){
                    that.students = res.data.data;
                    that.total = res.data.data.length;
                    that.getPageStudents();
                    that.$message({
                        message: '添加数据成功！',
                        type: 'success'
                    });    
                    that.closeDialogForm('studentForm');
                }
                else{
                    that.$message.error(res.data.msg);
                }
            })
            .catch(err=>{
                console.log(err);
                that.$message.error("查询结果出现异常");
            })
        },
        submitUpdateStudent(){
            let that = this;
            axios
            .post(that.baseURL + 'student/update/',that.studentForm)
            .then(res=>{
                if(res.data.code === 1){
                    that.students = res.data.data;
                    that.total = res.data.data.length;
                    that.getPageStudents();
                    that.$message({
                        message: '修改数据成功！',
                        type: 'success'
                    });    
                    that.closeDialogForm('studentForm');
                }
                else{
                    that.$message.error(res.data.msg);
                }
            })
            .catch(err=>{
                console.log(err);
                that.$message.error("修改出现异常");
            })
        },
        deleteStudent(row){
            this.$confirm('是否确认删除学生信息[学号:'+row.sno +'\t姓名:'+row.name+']信息？', '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let that = this;
                axios.post(that.baseURL + 'student/delete/',{sno:row.sno})
                .then(res=>{
                    if(res.data.code === 1){
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '删除数据成功！',
                            type: 'success'
                        });    
                    }
                    else{
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err=>{
                    console.log(err);
                    that.$message.error("删除出现异常");
                })
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });
        },
        deleteStudents(){
            this.$confirm("是否确认批量删除"+this.selectStudents.length+"个学生信息", '提示', {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                let that = this;
                axios.post(that.baseURL + 'students/delete/',{student:that.selectStudents})
                .then(res=>{
                    if(res.data.code === 1){
                        that.students = res.data.data;
                        that.total = res.data.data.length;
                        that.getPageStudents();
                        that.$message({
                            message: '批量删除数据成功！',
                            type: 'success'
                        });    
                    }
                    else{
                        that.$message.error(res.data.msg);
                    }
                })
                .catch(err=>{
                    console.log(err);
                    that.$message.error("删除出现异常");
                })
                this.$message({
                  type: 'success',
                  message: '批量删除成功!'
                });
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                });          
              });
        },
        closeDialogForm(formName) {
            this.$refs[formName].resetFields();
            let temp = {
                sno: '',
                name: '',
                gender: '',
                birthday: '',
                moblie: '',
                email: '',
                address: '',
                image: '',

            }
            this.studentForm = temp;
            this.dialogVisible = false;
            this.isView = false;
            this.isEdit = false;
        },
        handleSelectionChange(data){
            this.selectStudents = data;
            console.log(data);
        },
        uploadPicturePost(file) {
            let that = this;
            let fileReq = new FormData();
            fileReq.append('avatar', file);  // Change this line
        
            axios({
                method: 'post',
                url: that.baseURL + 'upload/',
                data: fileReq
            })
            .then(res => {
                if (res.data.code === 1) {
                    that.studentForm.image = res.data.name;
                    that.studentForm.imageUrl = that.baseURL + 'media/' + res.data.name;
                } else {
                    that.$message.error(res.data.msg);
                }
            })
            .catch(err => {
                console.log(err);
                that.$message.error("上传图像出现异常！");
            });
        },

    }
})